package xyz.lisys.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Bean
    public TokenStore tokenStore() {
        // DefaultTokenServices 默认的存储 Token 类

        return new InMemoryTokenStore();
    }

    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        return new InMemoryAuthorizationCodeServices();
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // client-id + client-secret 进行的客户端认证
        security
                .tokenKeyAccess("permitAll()") // oauth/token_key是公开
                .checkTokenAccess("permitAll()") // oauth/check_token公开
                .allowFormAuthenticationForClients(); // 表单认证（申请令牌）
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 用来配置客户端详情服务（ClientDetailsService），客户端详情信息在这里进行初始化，
        // 你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息
        // 当授权服务器完成用户认证并授予访问令牌后，它会将用户重定向回客户端指定的URI

        clients.inMemory() // 使用in-memory存储
                .withClient("client")// client_id
                .secret(new BCryptPasswordEncoder().encode("secret")) // 客户端密钥
                .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token") // 该client允许的授权类型authorization_code,password,refresh_token,implicit,client_credentials
                .scopes("all") // 允许的授权范围
                .autoApprove(false) // false跳转到授权页面
                .redirectUris("https://www.baidu.com"); // 加上授权码的回调地址
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 用来配置令牌（token）的访问端点和令牌服务(tokenservices)

        endpoints
                .authorizationCodeServices(authorizationCodeServices()) // 授权码服务
                .tokenStore(tokenStore()) // 令牌管理服务
                .authenticationManager(authenticationManager) // 密码认证服务
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);

        // 授权码认证模式
        // http://localhost:8080/auth/oauth/authorize?client_id=client&response_type=code&redirect_uri=https://www.baidu.com
        // http://localhost:8080/auth/oauth/token?client_id=client&client_secret=secret&grant_type=authorization_code&code=rC-bcW&redirect_uri=https://www.baidu.com

        // 密码认证模式
        // http://localhost:8080/auth/oauth/token?client_id=client&client_secret=secret&grant_type=password&username=admin&password=123456

        // 客户端凭证模式
        // http://localhost:8080/auth/oauth/token?client_id=client&client_secret=secret&grant_type=client_credentials

        // 简单模式
        // http://localhost:8080/auth/oauth/authorize?client_id=client&response_type=token&redirect_uri=https://www.baidu.com

        // 刷新令牌
        // http://localhost:8080/auth/oauth/token?client_id=client&client_secret=secret&grant_type=refresh_token&refresh_token=abc
    }
}
